<template>
  <div
    :key="containerId"
    :id="containerId"
    class="container"
    :class="isCreatePage && !noneOperation ? 'isCreatePage' : ''"
    v-show="approveCurrentList != []"
  >
    <div class="col" v-for="(item, index) in approveCurrentList" :key="index">
      <div
        v-for="(box, index) in item"
        :class="box.id"
        class="box"
        :id="box.id"
        :key="index"
        name="cell"
        :style="
          box.isApprovering == '1'
            ? box.type == 'Reject'
              ? 'border: 1px solid #FD8373;'
              : 'border: 1px solid #45b8fd;'
            : box.isApprovering == '2'
            ? 'border: 1px solid #5FE3A1;'
            : 'border: 1px solid #EBEBEB;'
        "
      >
        <div
          :class="
            box.isApprovering === '1'
              ? box.type == 'Reject'
                ? 'isReject'
                : 'isApprovering0'
              : box.isApprovering === '2'
              ? 'isApprovering1'
              : 'isApprovering2'
          "
        >
          {{ box.typeName || currentCardTitleRender(box.type) }}
        </div>

        <div class="body">
          <div :class="box.isApprovering === '1' ? 'unApprovername' : 'name'">
            <el-icon
              v-if="box.name == 'Finished'"
              class="el-icon-success"
              :size="14"
              :color="box.isApprovering == '1' ? '#45b8fd' : '#909399'"
              ><CircleCheckFilled
            /></el-icon>

            <el-tooltip
              placement="top"
              effect="light"
              popper-class="ApprovalProcessCurrentNamePopper"
            >
              <template #content>
                {{
                  box.name == 'Finished' || box.name == 'Reject'
                    ? box.name
                    : box.userName == null
                    ? box.name
                    : box.userName
                }}</template
              >

              {{
                box.name == 'Finished' || box.name == 'Reject'
                  ? box.name
                  : box.userName == null
                  ? box.name
                  : box.userName
              }}
            </el-tooltip>
          </div>

          <div
            class="time"
            v-if="box.isApprovering == '1' && box.name != 'Reject' && box.name != 'Finished'"
          >
            <el-icon class="el-icon-success" :size="14"><CircleCheckFilled /></el-icon>
            <span>{{ formatDate(box.approveDate, true) }}</span>
          </div>
          <div
            class="addCollaborate"
            v-if="
              (box.isApprovering == '2' && currentRow.status == '0' && !isCreatePage) ||
              (box.isApprovering == '2' &&
                currentRow.status == '2' &&
                currentRow.isHandle == '0' &&
                !isCreatePage)
            "
          >
            <div class="button" @click="collaborateRef.init()">
              <img class="icon" src="../assets/collaborate.png" />
              <span class="text">Collaborate</span>
            </div>

            <!-- assetCreateTeamwork 为请求接口  在index 点击approve 时传 -->
          </div>
        </div>
      </div>
    </div>

    <!-- <el-empty
  :key="containerId"
  v-show="showEmpty"
  description="No Data"
  style="display: flex; width: 100%"
  ></el-empty> -->
    <op-dialog-collaborate
      ref="collaborateRef"
      v-bind="{ ...collaborateConfig, recid: currentRow.recid }"
      @success="collaborateSuccess"
    />
  </div>
</template>

<script setup>
import { setUid } from '@/utils';
import jsPlumb from 'jsplumb';
import moment from 'moment';

const props = defineProps({
  currentRow: {
    //  当前行数据
    type: Object,
    required: true,
  },
  approveCurrentList: {
    // 审批流数据
    type: Array,
    required: true,
    default: () => [],
  },
  collaborateConfig: {
    // 协同配置项
    type: Object,
    default: () => {},
  },
  isCreatePage: {
    type: Boolean,
    required: false,
    default: false,
  },
  noneOperation: {
    type: Boolean,
    default: false,
    required: false,
  },
});

const emit = defineEmits(['success']);
//jsplumb使用
let $jsPlumb = jsPlumb.jsPlumb;
let jsPlumb_instance = null; // 缓存实例化的jsplumb对象

const containerId = ref('');
const connectList = ref([]);

// ref
const collaborateRef = ref();

onMounted(() => {
  // showPlumb();
  getApprovingList();
  window.addEventListener('resize', () => {
    // console.log('重绘啦');
    jsPlumb_instance.repaintEverything();
  });
});

onUnmounted(() => {
  // console.log('销毁');
  window.onresize = null;
});

//获取审批树状图
const getApprovingList = () => {
  // console.log('getApprovingList props.approveCurrentList', props.approveCurrentList);
  props.approveCurrentList.forEach((items, index) => {
    items.forEach(item => {
      if (props.approveCurrentList[index + 1]) {
        props.approveCurrentList[index + 1].forEach(i => {
          connectList.value.push({
            sourceNodeId: item.id,
            targetNodeId: i.id,
          });
        });
      }
    });
  });
  // console.log('getApprovingList connectList', connectList.value);
  nextTick(() => {
    initData();
  });
};

const initData = () => {
  showPlumb();
  jsPlumb_instance.repaintEverything();
};

const showPlumb = () => {
  jsPlumb_instance = $jsPlumb.getInstance({
    Container: setUid(),
    EndpointStyle: { radius: 0.11, fill: '#fff' },
    Connector: ['Flowchart', { gap: 1 }],
    DrapOptions: { cursor: 'crosshair', zIndex: 2000 },
  });
  // console.log(jsPlumb_instance);
  jsPlumb_instance.getAllConnections();
  jsPlumb_instance.batch(() => {
    initAll();
    connectionAll();
  });
  switchContainer(true, true, false);
};

const initAll = () => {
  props.approveCurrentList.forEach(item => {
    item.forEach(i => {
      init(i.id);
    });
  });
};

const connectionAll = () => {
  // console.log(jsPlumb_instance.ready);
  // console.log(connectList.value);
  jsPlumb_instance.ready(() => {
    connectList.value.forEach(item => {
      const conn = item;
      const connection = jsPlumb_instance.connect({
        source: conn.sourceNodeId,
        target: conn.targetNodeId,
        overlays: [
          [
            'Arrow',
            {
              width: 12,
              length: 10,
              location: 1,
              paintStyle: {
                stroke: '#D6D6D6',
                fill: '#D6D6D6',
              },
            },
          ],
        ],
      });
      connection.setPaintStyle({ stroke: '#D6D6D6', strokeWidth: 2 });
    });
  });
};

// 初始化规则使其可以连线、拖拽
const init = id => {
  const elem = document.getElementById(id);
  jsPlumb_instance.makeSource(elem, {
    anchor: ['Left', 'Right'],
    allowLoopback: false,
    maxConnections: -1,
  });
  jsPlumb_instance.makeTarget(elem, {
    anchor: ['Left', 'Right'],
    allowLoopback: false,
    maxConnections: -1,
  });
};

const collaborateSuccess = () => {
  // 通知主列表刷新
  emit('success');
};

const switchContainer = (target, source, draggable) => {
  const elem = document.getElementsByName('cell');
  jsPlumb_instance.setSourceEnabled(elem, draggable);
  jsPlumb_instance.setTargetEnabled(elem, draggable);
  jsPlumb_instance.setDraggable(elem, draggable); // 是否支持拖拽
};

const currentCardTitleRender = type => {
  switch (type) {
    case 'create':
      return 'APPLICANT';
    case 'coordination':
      return 'COLLABORATOR';
    case 'Reject':
      return 'REJECT';
    case 'forward':
      return 'FORWARD';
    case 'Finished':
      return 'FINISHED';
    default:
      return 'APPROVER';
  }
};

//修改时间格式
const formatDate = (date, istem) => {
  if (date == null || date == '') return '';
  if (istem) {
    return moment(date).format('DD/MM/YYYY');
  } else {
    return moment(date, 'YYYY-MM-DD HH:mm:ss').format('DD/MM/YYYY');
  }
};
</script>

<style lang="scss" scoped>
.container {
  display: flex;
  justify-content: space-between;
  position: relative;
  margin: 0 auto;
  width: 100%;
  height: 100%;
  // height: calc(100vh - 450px);
  .col {
    min-width: 280px;
  }
  .box {
    width: 180px;
    height: 90px;
    background: #ffffff;
    border-radius: 4px;

    margin-bottom: 10px;

    .isApprovering0 {
      width: 100%;
      height: 20px;
      background: #45b8fd;
      // border-radius: 4px 4px 0px 0px;
      color: #ffffff;
      font-size: 14px;
      line-height: 20px;
      margin: 0 auto;
      padding: 0;
      display: flex;
      justify-content: center;
    }
    .isApprovering1 {
      width: 100%;
      height: 20px;
      background: #5fe3a1;
      // border-radius: 4px 4px 0px 0px;
      color: #ffffff;
      font-size: 14px;
      line-height: 20px;
      margin: 0 auto;
      padding: 0;
      display: flex;
      justify-content: center;
    }
    .isApprovering2 {
      width: 100%;
      height: 20px;
      background: #ebebeb;
      // border-radius: 4px 4px 0px 0px;
      color: #ffffff;
      font-size: 14px;
      line-height: 20px;
      margin: 0 auto;
      padding: 0;
      display: flex;
      justify-content: center;
    }
    .isReject {
      width: 100%;
      height: 20px;
      background: #fd8373;
      // border-radius: 4px 4px 0px 0px;
      color: #ffffff;
      font-size: 14px;
      line-height: 20px;
      margin: 0 auto;
      padding: 0;
      display: flex;
      justify-content: center;
    }

    .isfinished {
      line-height: 90px;
      text-align: center;
      background: #ffffff;
      border-radius: 4px;
      font-size: 14px;
      font-weight: 400;
      color: #909399;
      .el-icon-success {
        // width: 14px;
        // height: 14px;
        margin-right: 100px;
      }
    }

    .body {
      background: #ffffff;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 68px;

      .unApprovername {
        text-align: center;
        background: #ffffff;
        font-size: 14px;
        font-weight: 400;
        color: #909399;
        word-break: break-all;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 1;
        // margin-top: 8px;
      }
      .name {
        text-align: center;
        background: #ffffff;
        font-size: 14px;
        font-weight: 400;
        color: #303133;

        padding: 0 2px;
        display: flex;
        align-items: center;

        word-break: break-all;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 1;
        // margin-top: 8px;
        .el-icon-success {
          // width: 14px;
          // height: 14px;
          margin-right: 10px;
        }
      }
      .addCollaborate {
        font-size: 14px;
        font-weight: 600;
        color: #127bbc;
        margin-top: 5px;

        .icon {
          color: #45b8fd;
          margin-right: 10px;
          cursor: pointer;
        }
        .text {
          cursor: pointer;
        }
      }
      .time {
        // height: 14px;
        font-size: 12px;
        font-weight: 400;
        color: #909399;

        word-break: break-all;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 1; /* 超出几行省略 */
        display: flex;
        align-items: center;
        .el-icon-success {
          color: #45b8fd;
          margin-right: 5px;
        }
      }
    }
    .isFinished {
      background: #ffffff;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      height: 68px;
      border-radius: 4px 4px 4px 4px;
    }
  }
}
.isCreatePage {
  // height: calc(30vh) !important;
}

.button {
  touch-action: none;
  color: #127bbc;
  cursor: pointer;
  img {
    margin: 0 10px 0 0;
  }
}
</style>
<style>
.ApprovalProcessCurrentNamePopper {
  max-width: 200px;
}
</style>
